<template>
  <div>
    <!-- 头部导航 -->
    <div class="search-result-container">
      <!-- 点击回退 -->
      <van-nav-bar
        title="搜索结果"
        left-arrow
        @click-left="$router.go(-1)"
        fixed
      >
      </van-nav-bar>
    </div>
    <!-- 文章列表 -->
    <div>
      <!-- 下拉加载更多 -->
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :immediate-check="false"
      >
        <!-- 遍历文章数据 -->
        <article-item
          v-for="item in articleList"
          :key="item.art_id"
          :artItem="item"
          :isShow="false"
          @click.native="itemClickFn(item.art_id)"
        >
        </article-item
      ></van-list>
    </div>
  </div>
</template>

<script>
import { searchResultListAPI } from "@/api";
import ArticleItem from "@/components/ArticleItem.vue";
export default {
  components: { ArticleItem },
  name: "SearchResult",
  data() {
    return {
      page: 1, //页码
      articleList: [], //文章列表数据
      loading: false, //加载状态
      finished: false, //是否全部加载完成
    };
  },
  async created() {
    const { data: res } = await searchResultListAPI({
      q: this.$route.params.keyword, //路由传参
      page: this.page,
    });
    // console.log(res);
    this.articleList = res.data.results;
  },
  methods: {
    async onLoad() {
      if (this.articleList.length > 0) {
        this.page++;
        const { data: res } = await searchResultListAPI({
          q: this.$route.params.keyword, //路由传参
          page: this.page,
        });
        if (res.data.results.length === 0) {
          // 没有更多数据了
          this.finished = true;
          return;
        }
        // console.log(res);
        // 合并数组
        this.articleList = [...this.articleList, ...res.data.results];
        //转化loading状态
        this.loading = false;
      }
    },
    // 跳转详情页事件
    itemClickFn(id) {
      // console.log(1111);
      this.$router.push({
        path: `/detail?art_id=${id}`,
      });
    },
  },
};
</script>

<style lang="less" scoped>
.van-nav-bar {
  background-color: #575b60;
}
/deep/ .van-nav-bar__title,
/deep/.van-nav-bar__arrow {
  color: #fff;
}

.search-result-container {
  padding-top: 46px;
}
</style>